import React, { useState, useEffect, useCallback, useRef } from 'react';
import { 
  Card, 
  Table, 
  Button, 
  Modal, 
  Form, 
  Input, 
  DatePicker, 
  message,
  Space,
  Tag,
  Popconfirm,
  Tooltip,
  Row,
  Col,
  Statistic
} from 'antd';
import { 
  PlusOutlined, 
  EditOutlined, 
  DeleteOutlined,
  PlayCircleOutlined,
  ClockCircleOutlined
} from '@ant-design/icons';
import dayjs from 'dayjs';
import './StudentLessons.scss';
import { request } from '@/utils/api';

const { TextArea } = Input;

const StudentLessons = ({ student, onClose }) => {
  const [lessons, setLessons] = useState([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingLesson, setEditingLesson] = useState(null);
  const [form] = Form.useForm();
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });
  const [studentInfo, setStudentInfo] = useState(student);
  const [stats, setStats] = useState({
    totalLessons: 0,
    totalDuration: 0,
    remainingLessons: 0
  });

  // 防抖状态
  const submitTimeoutRef = useRef(null);
  const deleteTimeoutRef = useRef(null);

  useEffect(() => {
    if (student?.id) {
      fetchLessons();
    }
  }, [student]);

  // 获取学生课时记录
  const fetchLessons = async (page = 1) => {
    setLoading(true);
    try {
      const data = await request(`/student/${student.id}/lessons?page=${page}&limit=${pagination.pageSize}`);

      if (data.code === 200) {
        setLessons(data.data.list);
        setPagination(prev => ({
          ...prev,
          current: data.data.page,
          total: data.data.total
        }));
        // 更新学生信息和统计信息
        setStudentInfo(data.data.student);
        setStats(data.data.stats);
      } else {
        message.error(data.message || '获取课时记录失败');
      }
    } catch (error) {
      console.error('获取课时记录失败:', error);
      message.error('网络错误，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  // 处理分页
  const handleTableChange = (paginationInfo) => {
    fetchLessons(paginationInfo.current);
  };

  // 打开新增/编辑弹窗
  const handleOpenModal = (lesson = null) => {
    setEditingLesson(lesson);
    setModalVisible(true);
    if (lesson) {
      form.setFieldsValue({
        lesson_title: lesson.lesson_title,
        lesson_date: dayjs(lesson.lesson_date),
        duration: lesson.duration,
        replay_url: lesson.replay_url,
        notes: lesson.notes
      });
    } else {
      form.resetFields();
      form.setFieldsValue({
        lesson_date: dayjs()
      });
    }
  };

  // 提交表单（使用防抖）
  const handleSubmit = useCallback(async (values) => {
    // 清除之前的定时器
    if (submitTimeoutRef.current) {
      clearTimeout(submitTimeoutRef.current);
    }

    // 设置新的定时器
    submitTimeoutRef.current = setTimeout(async () => {
      try {
        const submitData = {
          ...values,
          lesson_date: values.lesson_date
        };

        const url = editingLesson 
          ? `/student/${student.id}/lessons/${editingLesson.id}`
          : `/student/${student.id}/lessons`;
        
        const method = editingLesson ? 'PUT' : 'POST';

        const data = await request(url, {
          method,
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(submitData),
        });

        if (data.code === 200) {
          message.success(editingLesson ? '课时记录更新成功' : '课时记录添加成功');
          setModalVisible(false);
          fetchLessons(pagination.current);
        } else if (data.code === 429) {
          message.warning('操作过于频繁，请稍后再试');
        } else {
          message.error(data.message || '操作失败');
        }
      } catch (error) {
        console.error('操作失败:', error);
        message.error('网络错误，请稍后重试');
      }
    }, 1000); // 1秒防抖
  }, [editingLesson, student?.id, pagination.current, fetchLessons]);

  // 删除课时记录（使用防抖）
  const handleDelete = useCallback(async (lessonId) => {
    // 清除之前的定时器
    if (deleteTimeoutRef.current) {
      clearTimeout(deleteTimeoutRef.current);
    }

    // 设置新的定时器
    deleteTimeoutRef.current = setTimeout(async () => {
      try {
        const data = await request(`/student/${student.id}/lessons/${lessonId}`, {
          method: 'DELETE',
        });

        if (data.code === 200) {
          message.success('课时记录删除成功');
          fetchLessons(pagination.current);
        } else if (data.code === 429) {
          message.warning('操作过于频繁，请稍后再试');
        } else {
          message.error(data.message || '删除失败');
        }
      } catch (error) {
        console.error('删除失败:', error);
        message.error('网络错误，请稍后重试');
      }
    }, 500); // 0.5秒防抖
  }, [student?.id, pagination.current, fetchLessons]);

  // 表格列定义
  const columns = [
    {
      title: '课程标题',
      dataIndex: 'lesson_title',
      key: 'lesson_title',
      render: (title) => (
        <div className="lesson-title">{title}</div>
      )
    },
    {
      title: '上课日期',
      dataIndex: 'lesson_date',
      key: 'lesson_date',
      width: 120,
      render: (date) => (
        <div className="lesson-date">
          {dayjs(date).format('YYYY-MM-DD HH:mm')}
        </div>
      )
    },
    {
      title: '时长',
      dataIndex: 'duration',
      key: 'duration',
      width: 100,
      render: (duration) => (
        <div className="lesson-duration">
          <ClockCircleOutlined /> {duration}分钟
        </div>
      )
    },
    {
      title: '录播链接',
      dataIndex: 'replay_url',
      key: 'replay_url',
      width: 120,
      render: (url) => (
        <div className="replay-url">
          {url ? (
            <Tooltip title="点击观看录播">
              <Button 
                type="link" 
                icon={<PlayCircleOutlined />}
                onClick={() => window.open(url, '_blank')}
              >
                观看
              </Button>
            </Tooltip>
          ) : (
            <span className="no-url">无链接</span>
          )}
        </div>
      )
    },
    {
      title: '备注',
      dataIndex: 'notes',
      key: 'notes',
      render: (notes) => (
        <div className="lesson-notes">
          {notes || '-'}
        </div>
      )
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      render: (_, record) => (
        <Space size="small">
          <Tooltip title="编辑">
            <Button 
              type="link" 
              icon={<EditOutlined />} 
              onClick={() => handleOpenModal(record)}
            />
          </Tooltip>
          <Popconfirm
            title="确定要删除这条课时记录吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Tooltip title="删除">
              <Button 
                type="link" 
                danger
                icon={<DeleteOutlined />} 
              />
            </Tooltip>
          </Popconfirm>
        </Space>
      )
    }
  ];

  // 使用后端返回的统计信息

  return (
    <div className="student-lessons">
      {/* 统计信息 */}
      <Row gutter={16} className="stats-row">
        <Col span={6}>
          <Card>
            <Statistic
              title="总课时记录"
              value={stats.totalLessons}
              suffix="条"
              prefix={<ClockCircleOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="总上课时长"
              value={stats.totalDuration}
              suffix="分钟"
              prefix={<ClockCircleOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="剩余课时"
              value={parseFloat(stats.remainingLessons || 0).toFixed(2)}
              suffix="课时"
              prefix={<ClockCircleOutlined />}
              valueStyle={{ color: parseFloat(stats.remainingLessons || 0) > 0 ? '#52c41a' : '#ff4d4f' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="已用课时"
              value={parseFloat(studentInfo?.used_lessons || 0).toFixed(2)}
              suffix="课时"
              prefix={<ClockCircleOutlined />}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
      </Row>

      {/* 操作按钮 */}
      <Card 
        title="课时记录管理" 
        className="lessons-card"
        extra={
          <Space>
            <Button 
              type="primary" 
              icon={<PlusOutlined />}
              onClick={() => handleOpenModal()}
              disabled={parseFloat(stats.remainingLessons || 0) <= 0}
            >
              添加课时记录
            </Button>
            <Button onClick={onClose}>
              关闭
            </Button>
          </Space>
        }
      >
        <Table
          columns={columns}
          dataSource={lessons}
          rowKey="id"
          loading={loading}
          pagination={{
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => 
              `第 ${range[0]}-${range[1]} 条，共 ${total} 条记录`
          }}
          onChange={handleTableChange}
        />
      </Card>

      {/* 新增/编辑弹窗 */}
      <Modal
        title={editingLesson ? '编辑课时记录' : '添加课时记录'}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        footer={null}
        width={600}
        destroyOnHidden
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
        >
          <Form.Item
            name="lesson_title"
            label="课程标题"
            rules={[
              { required: true, message: '请输入课程标题' }
            ]}
          >
            <Input placeholder="请输入课程标题" />
          </Form.Item>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="lesson_date"
                label="上课日期"
                rules={[
                  { required: true, message: '请选择上课日期' }
                ]}
              >
                <DatePicker 
                  showTime 
                  format="YYYY-MM-DD HH:mm"
                  placeholder="请选择上课日期"
                  style={{ width: '100%' }}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="duration"
                label="上课时长（分钟）"
                rules={[
                  { required: true, message: '请输入上课时长' },
                ]}
              >
                <Input 
                  type="decimal" 
                  placeholder="请输入上课时长" 
                  min={1}
                />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="replay_url"
            label="录播链接"
          >
            <Input placeholder="请输入录播链接（可选）" />
          </Form.Item>

          <Form.Item
            name="notes"
            label="备注"
          >
            <TextArea 
              placeholder="请输入备注信息（可选）" 
              rows={3}
            />
          </Form.Item>

          <Form.Item>
            <Space>
              <Button 
                type="primary" 
                htmlType="submit"
              >
                {editingLesson ? '更新' : '添加'}
              </Button>
              <Button onClick={() => setModalVisible(false)}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default StudentLessons; 